//var $;
var gBrowser;

var CultureMuncher = {
	Workflow: CultureMuncher_Workflow,
	htmldoc: null,
	mainWindow: null,
	canvas: null,
	// init culture muncher
	onLoad: function(browser) {
		gBrowser = browser;

		// initialization code
		this.initialized = true;
		this.strings = document.getElementById("culturemuncher-strings");

		// init inspector
		CultureMuncher_Inspector.init();
		// listen to tab select
		browser.addEventListener("TabSelect", this.tabSelected, true);
		// listen to the loaded page
		browser.addEventListener('load', this.onPageLoad, true);
		// make sure it has registered pageload
		browser.addEventListener('load', CultureMuncher_Inspector.onPageLoad, true);
	},
	// disable culturemuncher
	onUnLoad: function(browser) {
		// listen to the loaded page
		browser.removeEventListener('load', this.onPageLoad, true);
	},
	// add page listeners
	onPageLoad: function(aEvent) {
		var doc = aEvent.originalTarget;
		if ((aEvent.originalTarget.nodeName == '#document') &&
		   (aEvent.originalTarget.defaultView.location.href == gBrowser.currentURI.spec)) {
           
			this.htmldoc = doc;

			// now load workflow
			if (doc != null && doc.URL != null && doc.URL != 'about:blank') {
				CultureMuncher.loadWorkflow(doc.URL);
			}

		}
	},
	loadWorkflow: function(url) {
		var workflows = CultureMuncher_Workflow.selectWorkflow(url);
		if (workflows != null) {
			// initialize workflow
			CultureMuncher_Workflow.init(workflows[0].Workflow, 0);
		}
		// now append workflow to canvas
		CultureMuncher_Workflow.createControl(document, CultureMuncher.canvas);
	},
	setActiveElement: function(elem) {
		this.activeElement = elem;

	},
	tabSelected: function(event) {
		var browser = gBrowser.selectedBrowser;
		// browser is the XUL element of the browser that's just been selected
		CultureMuncher.loadWorkflow(browser.contentDocument.URL);
	}
};